package net.lcheng.shop.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.lcheng.commons.utils.ParseMD5;
import net.lcheng.model.*;
import net.lcheng.service.*;
import net.lcheng.service.impl.UserServiceImpl;
import net.lcheng.shop.vo.CurrentUserModel;
import net.lcheng.utils.MobileMessageSend;
import net.lcheng.vo.UpdatePhoneModel;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import java.io.IOException;
import java.util.Date;

/**
 * Created by zwr on 2016/6/29 0029.
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private BaseVerificationCodeService codeService;
    @Autowired
    private UserServiceImpl getUserByPhone;
    @Autowired
    private UserShippingAddressService userShippingAddressService;
    @Autowired
    private UserBankcardService userBankcardService;
    @Autowired
    private WxShopService wxShopService;
    /**
     * 获取个人资料
     * 个人资料包含： 头像、手机号、昵称、登录密码、学习资料
     */
    @RequestMapping(value = "/user/data", method = RequestMethod.GET)
    public String dataGet(Model model) {
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            //获取当前用户
            Session session = currentUser.getSession();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            //查看用户是不是有店铺如果有店铺就显示店铺设置
            WxShop shop = wxShopService.getShopInforByUserIdAndShopStatus(currentUserModel.getUserId(),2);
            if (shop!=null){
                model.addAttribute("shop",shop);
            }
            String userId = currentUserModel.getUserId();
            //获取用户资料
            User user = userService.getUserByUserId(userId);
            model.addAttribute("userName", user.getUserName());
            //获取手机号码
            String userByPhone = user.getUserPhone();
            //判断用户手机号码是不是11位数然后用****的方式放到页面(保护用户隐私)
            if (userByPhone!=null&&userByPhone.length()==11){
                String phone = userByPhone.substring(0,userByPhone.length()-(userByPhone.substring(3)).length())+"****"+userByPhone.substring(7);
                model.addAttribute("phone", phone);
            }else{
                model.addAttribute("phone", user.getUserPhone());
            }
            model.addAttribute("user", user);
            /**获取地址*/
            UserShippingAddress userShippingAddress=userShippingAddressService.getAddressByUserId(userId);
              model.addAttribute("userShippingAddress",userShippingAddress);
            /**获取银行卡*/
            UserBankcard userBankcard=userBankcardService.getUserBankcardByUserId(userId);
            model.addAttribute("userBankcard",userBankcard);
        }else{
            return "redirect:/login";
        }
        return "data";
    }
    /**
     * 填写手机
     */
    @RequestMapping(value = "/user/update_phone", method = RequestMethod.GET)
    public String updatePhoneGet(Model model) {
        // 获取当前用户
        Subject currentUser = SecurityUtils.getSubject();
        //判断用户有没有登录
        if (currentUser.isAuthenticated()) {
            //获取当前用户
            Session session = currentUser.getSession();
           CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            String userId = currentUserModel.getUserId();
            //获取当前用户对象
            User user = userService.getUserByUserId(userId);
            model.addAttribute("user",user);

            System.out.println(user.getUserPhone());
            model.addAttribute("userPhone", user.getUserPhone());
            String userByPhone = user.getUserPhone();
            //判断用户手机号是不是有11位数如果是用***方式显示在页面
            if (userByPhone!=null&&userByPhone.length()==11){
                String phone = userByPhone.substring(0,userByPhone.length()-(userByPhone.substring(3)).length())+"****"+userByPhone.substring(7);
                model.addAttribute("phone", phone);
            }else {
                //填充model
                model.addAttribute("phone", user.getUserPhone());
            }
        }else{
            return "redirect:/login";
        }
        return "update_phone";
    }
    /**
     * 填写手机，保存
     */
    @RequestMapping(value = "/user/update_phone", method = RequestMethod.POST)
    public String savingPhonePost(Model model, @ModelAttribute("PhoneModel") UpdatePhoneModel phoneModel, Errors errors, @RequestParam("userPhone") String userPhone, @RequestParam("number") String number, @RequestParam("number") String verifyCode, @RequestParam("userPwd") String userPwd,  RedirectAttributesModelMap modelMap, BindingResult result) {

        /**检验输入的验证码是否过期了*/
        BaseVerificationCode code = codeService.getByPhoneAndCode(userPhone, verifyCode);
        if (code != null) {
            //验证码过期,刷新修改页面
            if (new Date().after(code.getExpirationTime())) {
                modelMap.addFlashAttribute("errorType", 2);
                modelMap.addFlashAttribute("error", "验证码过期");
                return "redirect:/user/update_phone";
            } else {
                Subject currentUser = SecurityUtils.getSubject();
                //获取当前用户
                Session session = currentUser.getSession();
               CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
                String userId = currentUserModel.getUserId();
                User user = userService.getUserByUserId(userId);
                //判断如果是微信登录没有手机号码就绑定手机号如果有手机号码就解绑手机号码(获取原来的手机号码然后下一步绑定新手机号码)
                System.out.println(user.getUserPhone()==null||user.getUserPhone().length()==0);
                //如果绑定了手机号码就跳转下一步
                if (user.getUserPhone()==null||user.getUserPhone().length()==0){
                      //获取User手机号码
                      User userModel = getUserByPhone.getUserByPhone(phoneModel.getUserPhone());
                      //进行判断如果数据库有这个手机号码就不让他填写手机号码
                      if (userModel != null) {
                        modelMap.addFlashAttribute("errorType", 1);
                        modelMap.addFlashAttribute("error", "该手机号码存在");
                        return "redirect:/user/update_phone";
                    }
                        userService.updatePassword(userId, ParseMD5.parseStrToMd5L32(userPwd),userPhone );
                        return "redirect:/user/data";
                }else{
                    return "redirect:/user/modify_phone";
                }
            }
        } else {
            modelMap.addFlashAttribute("errorType", 4);
            modelMap.addFlashAttribute("error", "验证码错误");
            return "redirect:/user/update_phone";
        }
    }
    /***填写新的手机号码Get*/
    @RequestMapping(value = "/user/modify_phone", method = RequestMethod.GET)
    public String modifyPhoneGet(Model model) {

        return "my/modify_phone";
    }

    /**
     * 填写手机，保存Post
     */
    @RequestMapping(value = "/user/modify_phone", method = RequestMethod.POST)
    public String modifyPhonePost(Model model, @RequestParam("userPhone") String userPhone, @RequestParam("number") String verifyCode, RedirectAttributesModelMap modelMap) {
        User userModel = getUserByPhone.getUserByPhone(userPhone);
        if (userModel != null) {
            modelMap.addFlashAttribute("errorType", 4);
            modelMap.addFlashAttribute("error", "该手机号码存在");
            return "redirect:/user/modify_phone";
        }
        /**检验输入的验证码是否过期了*/
        BaseVerificationCode code = codeService.getByPhoneAndCode(userPhone, verifyCode);
        if (code != null) {
            //验证码过期,刷新修改页面
            if (new Date().after(code.getExpirationTime())) {
                modelMap.addFlashAttribute("errorType", 1);
                modelMap.addFlashAttribute("error", "验证码过期");
                return "redirect:/user/modify_phone";
            } else {
                if (verifyCode==null||verifyCode=="") {
                    modelMap.addFlashAttribute("errorType", 2);
                    model.addAttribute("error", "请输入验证码");
                    return "redirect:/user/modify_phone";
                }
                Subject currentUser = SecurityUtils.getSubject();
                //获取当前用户
                Session session = currentUser.getSession();
               CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
                String userId = currentUserModel.getUserId();
                //更新手机号
                userService.updatePhone(userId, userPhone);
            }
        } else {
            modelMap.addFlashAttribute("errorType", 3);
            modelMap.addFlashAttribute("error", "验证码错误");
            return "redirect:/user/modify_phone";
        }
        //返回个人资料页
        modelMap.addFlashAttribute("error", "修改手机号码成功请重新登录");
        return "redirect:/sign";
    }
    /**
     * 修改昵称
     */
    @RequestMapping(value = "/user/update_name", method = RequestMethod.GET)
    public String updateNameGet(Model model) {
        //获取当前用户id
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            //获取当前用户
            Session session = currentUser.getSession();
           CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            String userId = currentUserModel.getUserId();
            //获取当前用户对象，然后填充model
            User user = userService.getUserByUserId(userId);
            model.addAttribute("name", user.getUserName());
        }
        return "my/update_name";
    }
    /**
     * 修改昵称，保存
     */
    @RequestMapping(value = "/user/update_name", method = RequestMethod.POST)
    public String savingNamePost(String userName) {
        //获取当前用户id
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            //获取当前用户
            Session session = currentUser.getSession();
           CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            String userId = currentUserModel.getUserId();
            //更新昵称
            userService.updateName(userId, userName);
        }
        //返回个人资料页
        return "redirect:/user/data";
    }
    /**
     * 修改密码
     */
    @RequestMapping(value = "/user/update_password", method = RequestMethod.GET)
    public String updatePasswordGet(Model model) {
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            //  获取当前用户
            Session session = currentUser.getSession();
           CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            String userId = currentUserModel.getUserId();
            //获取当前用户对象，然后填充model
            User user = userService.getUserByUserId(userId);
            model.addAttribute("phone", user.getUserPhone());
            //判断有没有密码和手机号如果没有就先绑定手机
            if (user.getUserPwd() == null || user.getUserPwd().length() == 0 || user.getUserPhone() == null || user.getUserPhone().length() == 0) {
                return "redirect:/user/update_phone";
            }
        }else{
            return "redirect:/login";
        }
            return "my/update_password";
         }
    /**
     * 修改密码，保存
     */
    @RequestMapping(value = "/user/update_password", method = RequestMethod.POST)
    public String savingPasswordPost(Model model, @RequestParam("userPwd") String userPwd, @RequestParam("password") String password,  RedirectAttributesModelMap modelMap) {
        Subject currentUser = SecurityUtils.getSubject();
       // 获取当前用户
        Session session = currentUser.getSession();
       CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
        User user = userService.getUserByUserId(currentUserModel.getUserId());
        //获取用户输入的原密码
        String inputPwd = ParseMD5.parseStrToMd5L32(password);
        //获取原密码判断是不是输入正确
        if (!user.getUserPwd().equals(inputPwd)) {
            modelMap.addFlashAttribute("errorType", 1);
            modelMap.addFlashAttribute("error", "原密码不正确请重新输入");
            return "redirect:/user/update_password";
        }
        String userPassword = ParseMD5.parseStrToMd5L32(userPwd);
        //获取用户输入的新密码判断用户是不是和原来密码相同
        if (user.getUserPwd().equals(userPassword)){
            modelMap.addFlashAttribute("errorType", 2);
            modelMap.addFlashAttribute("error", "新密码不能和近期密码相同");
            return "redirect:/user/update_password";
        }
        //更新密码
        userService.updatePassword(user.getUserId(), ParseMD5.parseStrToMd5L32(userPwd));
        return "redirect:/sign";
    }

    /**
     * 判断手机号码
     *
     * @return zwr
     */
    @RequestMapping("/checkPassword")
    @ResponseBody
    public String checkPassword(String phoneNum) {
        Subject currentUser = SecurityUtils.getSubject();
        //获取当前用户
        Session session = currentUser.getSession();
       CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);

        User userInfor = userService.getUserByUserId(currentUserModel.getUserId());
        //获取用户输入的手机号码进行验证
        User userModel = getUserByPhone.getUserByPhoneByUserId(userInfor.getUserPhone(), currentUserModel.getUserId());
        if (userModel.getUserPhone().equals(phoneNum)) {
            return "yes";
        } else {
            return "no";
        }

    }

    /**
     * 发送验证码
     *
     * @return
     */
    @RequestMapping("/user/sendingVerificationCodeAjax/{phone}")
    public
    @ResponseBody
    int sendingVerificationCodeAjax(@PathVariable("phone") String phoneNum) throws IOException {
        /**生成验证码，并保存验证码*/
        String verifyCode = codeService.insert(phoneNum, 1);
        /**保存成功，就发送验证码*/
        //int sendStatus = MessageUtils.sendMsg(phoneNum, "验证码" + verifyCode + "[有效期10分钟]" + "如非本操作请及时修改密码");
        int sendStatus = MobileMessageSend.sendMsg(phoneNum,verifyCode);
        System.out.println("您你的验证码是"+verifyCode);
        //发送成功返回0
        return sendStatus;
    }
}
